package com.twobu.twobuinsight.interceptor;

import com.twobu.twobuinsight.security.UserContext;
import com.twobu.twobuinsight.security.UserContextHolder;
import com.twobu.twobuinsight.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            // token = token.substring(7);
        } else {
            // 如果请求头中没有token，尝试从session中获取
            HttpSession session = request.getSession(false);
            if (session != null) {
                token = (String) session.getAttribute("token");
            }
        }

        if (token != null && !token.isEmpty()) {
            // 验证token
            UserContext userContext = authService.validateToken(token);
            if (userContext != null) {
                // 将用户信息存入ThreadLocal
                UserContextHolder.setUserContext(userContext);

                // 将token存入session，方便下次使用
                HttpSession session = request.getSession(true);
                session.setAttribute("token", token);
                session.setAttribute("userContext", userContext);

                // 设置session过期时间
                session.setMaxInactiveInterval(7200); // 2小时

                return true;
            }
        }

        // 如果是登录、注册等不需要认证的接口，直接放行
        String requestURI = request.getRequestURI();
        if (isExcludedUri(requestURI)) {
            return true;
        }

        // 认证失败，返回401
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"message\":\"未登录或登录已过期\"}");

        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后清除ThreadLocal中的用户信息，防止内存泄漏
        UserContextHolder.clear();
    }

    /**
     * 判断是否是不需要认证的URI
     */
    private boolean isExcludedUri(String uri) {
        return uri.startsWith("/auth/login") ||
               uri.startsWith("/test") ||
               uri.startsWith("/swagger-ui") ||
               uri.startsWith("/swagger-resources") ||
               uri.startsWith("/v3/api-docs") ||
               uri.startsWith("/doc.html") ||
               uri.startsWith("/webjars");
    }
}
